package com.rockcent.mall.controller;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.Routes;
import com.rockcent.mall.lib.domain.Template;
import com.rockcent.mall.lib.domain.enumclass.TemplateType;
import com.rockcent.mall.lib.dto.TemplateDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.helper.TemplateHelper;
import com.rockcent.mall.lib.repository.TemplateRepository;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;

/**
 * 模板管理包含功能：
 * 新增、修改、删除、查询信息、查询列表
 * Created by zhangjh on 2016/11/16.
 */
@RestController
public class TemplateController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(TemplateController.class);

    @Autowired
    private BaseUserHelper userHelper;


    @Autowired
    private TemplateRepository templateRepository;


    @Autowired
    private TemplateHelper templateHelper;



    /**
     * @api {post} /mall/mobile/templates/save M端 新增模板
     * @apiGroup mall_mobiletemplate
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} title <code>必须参数</code> 专题标题
     * @apiParam {String} type <code>必须参数</code> 专题描述
     * @apiParam {String} content <code>必须参数</code>  编辑内容
     *  "[{'pic_path':'/abc/1.jpg','type':'0','url':'www.baidu.com'}]"
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "version": 0,
     *     "mallId": 1,
     *     "title": "图片01",
     *     "type": "TYPE_FIRST",
     *     "content": "[{'pic_path':'/abc/1.jpg','type':'0','url':'www.baidu.com'}]",
     *     "seqNo": 11
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_MOBILE_TEMPLATE_SAVE, method = RequestMethod.POST)
    public JsonResult addInfo(@RequestBody TemplateDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (dto == null) {
                jsonResult.errorParam("template信息为空", log);
                return;
            }

            if(!EnumUtils.isValidEnum(TemplateType.class,dto.getType().toString())){
                jsonResult.errorParam("模板类型选择错误", log);
                return;
            }

            if (dto.getTitle() == null) {
                jsonResult.errorParam("标题为空", log);
                return;
            }
            if (dto.getContent() == null) {
                jsonResult.errorParam("编辑内容为空", log);
                return;
            }

            Template template = templateHelper.chgCtoToDomain(dto);
            template.setIsDelete(Whether.NO);
            template.setMallId(mallId);

            Template maxTemplate = templateRepository.findTop1ByIsDeleteOrderBySeqNoDesc( Whether.NO);
            Integer maxSeqno =0;
            if(null!=maxTemplate){
                maxSeqno = maxTemplate.getSeqNo();
            }
            Integer nextNo = maxSeqno + 1;
            template.setSeqNo(nextNo);

            templateRepository.save(template);
            jsonResult.data = template;
        };
        return doing.go(request, log);
    }




    /**
     * @api {get} /mall/mobile/templates/info M端 查询模板
     * @apiGroup mall_mobiletemplate
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} id <code>必须参数</code> 记录id
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 1,
     *     "dateCreated": "2016-11-16 19:03:56",
     *     "lastUpdated": "2016-11-16 19:03:56",
     *     "version": 0,
     *     "mallId": 1,
     *     "title": "图片01",
     *     "type": "TYPE_FIRST",
     *     "content": "[{'pic_path':'/abc/1.jpg','type':'0','url':'www.baidu.com'}]",
     *     "seqNo": 1
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_MOBILE_TEMPLATE, method = RequestMethod.GET)
    public JsonResult queryInfo(@RequestParam("id") Long id, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (null == id) {
                jsonResult.errorParam("ID不能为空", log);
                return;
            }
            Template template = templateRepository.findByIdAndIsDelete(id, Whether.NO);
            if (template == null) {
                jsonResult.errorParam("加载template信息失败", log);
                return;
            }
            Long mallIdDb = template.getMallId();
            if (mallId != mallIdDb) {
                jsonResult.errorParam("没查询权限", log);
                return;
            }
            jsonResult.data = template;

        };
        return doing.go(request, log);

    }


    /**
     * @api {put} /mall/mobile/templates/delete/ M端 删除模板
     * @apiGroup mall_mobiletemplate
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} id <code>必须参数</code> 记录id
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_TEMPLATE_DELETE, method = RequestMethod.PUT)
    public JsonResult deleteInfo(@RequestBody TemplateDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            Long id = dto.getId();
            if (null == id) {
                jsonResult.errorParam("ID不能为空", log);
                return;
            }
            Template template = templateRepository.findByIdAndIsDelete(id, Whether.NO);
            if (template == null) {
                jsonResult.errorParam("加载template信息失败", log);
                return;
            }
            Long mallIdDb = template.getMallId();
            if (mallId != mallIdDb) {
                jsonResult.errorParam("没有删除权限", log);
                return;
            }
            template.setIsDelete(Whether.YES);
            templateRepository.save(template);
        };
        return doing.go(request, log);
    }



    /**
     * @api {put} /mall/mobile/templates/update M端 修改模板
     * @apiGroup mall_mobiletemplate
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} title <code>必须参数</code> 专题标题
     * @apiParam {String} type <code>必须参数</code> 专题描述
     * @apiParam {String} content <code>必须参数</code>  编辑内容
     *  "[{'pic_path':'/abc/1.jpg','type':'0','url':'www.GOOGE.com'}]"
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *     "id": 2,
     *     "dateCreated": "2016-11-16 19:21:32",
     *     "lastUpdated": "2016-11-16 19:21:32",
     *     "version": 1,
     *     "mallId": 1,
     *     "title": "图片01x",
     *     "type": "TYPE_SECOND",
     *     "content": "[{'pic_path':'/abc/1.jpg','type':'0','url':'www.GOOGE.com'}]",
     *     "seqNo": 2
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_MOBILE_TEMPLATE_UPDATE, method = RequestMethod.PUT)
    public JsonResult updateInfo(@RequestBody TemplateDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (dto == null) {
                jsonResult.errorParam("template信息为空", log);
                return;
            }
            Long id = dto.getId();
            if (dto.getId() == null) {
                jsonResult.errorParam("记录id为空", log);
                return;
            }

            if(!EnumUtils.isValidEnum(TemplateType.class,dto.getType().toString())){
                jsonResult.errorParam("模板类型选择错误", log);
                return;
            }

            if (dto.getTitle() == null) {
                jsonResult.errorParam("标题为空", log);
                return;
            }
            if (dto.getContent() == null) {
                jsonResult.errorParam("编辑内容为空", log);
                return;
            }


            Template template = templateRepository.findByIdAndIsDelete(id, Whether.NO);
            if (template == null) {
                jsonResult.remind(template.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            Long mallIdDb = template.getMallId();
            if (mallId != mallIdDb) {
                jsonResult.errorParam("没修改权限", log);
                return;
            }
            template.setTitle(dto.getTitle());
            template.setContent(dto.getContent());
            template.setType(TemplateType.valueOf(dto.getType()));

            templateRepository.save(template);

            jsonResult.data = template;
        };
        return doing.go(request, log);
    }


    /**
     * @api {get} /mall/mobile/templates/list M端 搜索template
     * @apiGroup mall_mobiletemplate
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize 每页记录数
     * @apiSuccessExample {json} Success-Response:
     * {
     *     "code":"1",
     *     "desc":"成功",
     *     "data":{
     *         "data":[
     *             {
     *                 "id":7,
     *                 "dateCreated":"2016-11-16 19:33:08",
     *                 "lastUpdated":"2016-11-16 19:33:08",
     *                 "version":0,
     *                 "mallId":1,
     *                 "title":"图片01",
     *                 "type":"TYPE_FIRST",
     *                 "content":"[{'pic_path':'/abc/1.jpg','type':'0','url':'www.baidu.com'}]",
     *                 "seqNo":7
     *             }
     *         ],
     *         "totalCount":17,
     *         "totalPage":4,
     *         "pageNo":1,
     *         "pageSize":5
     *     }
     * }
     *
     *
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_TEMPLATE_LIST, method = RequestMethod.GET)
    public JsonResult listInfo(TemplateDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if (dto == null) {
                jsonResult.errorParam("template信息为空", log);
                return;
            }

            PageResult<Template> pageResult = templateRepository.findTemplateQuery(mallId,Whether.NO,this.getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.setUrl(Routes.MALL_MOBILE_TEMPLATE_LIST);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }



    /**
     * @api {put} /mall/mobile/templates/sort M端 模板调整排序
     *
     * @apiGroup mall_mobileTemplate
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String=UP("前移"), DOWN("后移")} direction <code>必选参数</code> 类型
     * @apiParam {Long} id <code>必选参数</code> 记录id
     * @apiSuccessExample {json} Success-Response:
     * {
     *  "code": "1",
     *  "desc": "成功"
     * }
     */
    @RequestMapping(value = Routes.MALL_MOBILE_TEMPLATE_SORT, method = RequestMethod.PUT)
    public JsonResult sort(@RequestBody TemplateDto dto, HttpServletRequest request) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();

        RestDoing doing = jsonResult -> {

            if (dto == null) {
                jsonResult.errorParam("TEMPLATE信息为空", log);
                return;
            }

            Long id = dto.getId();
            if (dto.getId() == null) {
                jsonResult.errorParam("记录id为空", log);
                return;
            }

            String direction = dto.getDirection();
            if (StringUtils.isBlank(direction)) {
                jsonResult.errorParam("请添加调整顺序按钮", log);
                return;
            } else if (!direction.equals(Template.UP) && !direction.equals(Template.DOWN)) {
                jsonResult.errorParam("direction数据内容错误", log);
                return;
            }

            Template template = templateRepository.findByIdAndIsDelete(id,Whether.NO);
            if (template == null) {
                jsonResult.remind(Template.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            //查询受影响的模板
            Template aboutTemplate = templateRepository.findTemplateAbout(template.getSeqNo(),mallId, direction);
            if(null==aboutTemplate){
                jsonResult.remind("不能继续调整顺序",log);
                return;
            }
            int tem0 = aboutTemplate.getSeqNo();
            int tem1 = template.getSeqNo();
            aboutTemplate.setSeqNo(tem1);
            template.setSeqNo(tem0);

            templateRepository.save(template);

            templateRepository.save(aboutTemplate);
//            jsonResult.data = templates;
        };


        return doing.go(request, log);


    }


}




